from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import Optional
from config.database import get_db
from models import Book
from schemas import ResponseModel, BookResponse, BookListResponse, PaginationParams
from auth import get_current_user
import math

router = APIRouter()

@router.get("/search", response_model=ResponseModel)
async def search_books(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    current_user = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """搜索图书"""
    # 构建查询
    query = db.query(Book).filter(Book.is_active == True)
    
    # 如果有关键词，进行模糊搜索
    if keyword:
        search_filter = or_(
            Book.title.contains(keyword),
            Book.author.contains(keyword),
            Book.publisher.contains(keyword),
            Book.keywords.contains(keyword)
        )
        query = query.filter(search_filter)
    
    # 计算总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * page_size
    books = query.offset(offset).limit(page_size).all()
    
    # 转换为响应模型
    book_responses = [BookResponse.from_orm(book) for book in books]
    
    # 计算总页数
    total_pages = math.ceil(total / page_size)
    
    # 构造响应
    book_list_response = BookListResponse(
        books=book_responses,
        total=total,
        page=page,
        page_size=page_size,
        total_pages=total_pages
    )
    
    return ResponseModel(
        code=200,
        message="搜索成功",
        data=book_list_response
    )

@router.get("/recommendations", response_model=ResponseModel)
async def get_recommendations(
    limit: int = Query(10, ge=1, le=50, description="推荐数量"),
    current_user = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取推荐图书"""
    # 简单的推荐逻辑：返回最新添加的图书
    books = db.query(Book).filter(
        Book.is_active == True,
        Book.available_stock > 0
    ).order_by(Book.created_at.desc()).limit(limit).all()
    
    book_responses = [BookResponse.from_orm(book) for book in books]
    
    return ResponseModel(
        code=200,
        message="获取推荐成功",
        data=book_responses
    )